<template>
  <a-row :gutter="24">
    <a-col :md="24">
      <a-card :style="cardStyle" :bordered="false">
        <!-- 查询区域 -->
        <div class="table-page-search-wrapper">
          <!-- 搜索区域 -->
          <a-form layout="inline" @keyup.enter.native="searchQuery">
            <a-row :gutter="24"  >
              <a-col :md="6" :sm="24" style="display:none;">
                <a-form-item label="类别" :labelCol="labelCol" :wrapperCol="wrapperCol">
                  <a-tree-select style="width:100%" :dropdownStyle="{maxHeight:'200px',overflow:'auto'}" allow-clear
                   :treeData="categoryTree" v-model="queryParam.categoryId" placeholder="请选择类别">
                  </a-tree-select>
                </a-form-item>
              </a-col>
              <a-col :md="6" :sm="24">
                <a-form-item label="(项目名)关键词" :labelCol="labelCol" :wrapperCol="wrapperCol">
                  <a-input placeholder="请输入项目名关键词" v-model="queryParam.materialParam" ref="search"></a-input>
                </a-form-item>
              </a-col>
              <a-col :md="6" :sm="24"  style="display:none;">
                <a-form-item label="颜色" :labelCol="labelCol" :wrapperCol="wrapperCol">
                  <a-input placeholder="请输入颜色查询" v-model="queryParam.color"></a-input>
                </a-form-item>
              </a-col>
              <span style="float: left;overflow: hidden;" class="table-page-search-submitButtons">
                <a-col :md="6" :sm="24">
                  <a-button type="primary" @click="projectQuery">查询</a-button>
                  <a-button style="margin-left: 8px" @click="searchReset">重置</a-button>
                  <!-- <a @click="handleToggleSearch" style="margin-left: 8px">
                    {{ toggleSearchStatus ? '收起' : '展开' }}
                    <a-icon :type="toggleSearchStatus ? 'up' : 'down'"/>
                  </a> -->
                </a-col>
              </span>
              <template v-if="toggleSearchStatus"  >           
                <a-col :md="6" :sm="24" style="display:none;">
                  <a-form-item label="备注" :labelCol="labelCol" :wrapperCol="wrapperCol">
                    <a-input placeholder="请输入备注查询" v-model="queryParam.remark"></a-input>
                  </a-form-item>
                </a-col>
              </template>
            </a-row>
          </a-form>
        </div>
        <!-- 操作按钮区域 -->
        <div class="table-operator"  style="margin-top: 5px">
          <a-button  @click="handleAdd" type="primary" icon="plus">新增项目</a-button>
          <a-button  @click="handleAddSub" type="primary" icon="plus">新增子表</a-button> 
          <a-upload name="file" :showUploadList="false" :multiple="false" :headers="tokenHeader" :action="importExcelUrl"  :beforeUpload="beforeUpload" @change="handleImportExcel">
            <!-- <a-popover title="表格模板">             -->
              <a-button type="primary" icon="import">导入</a-button>
            <!-- </a-popover> -->
          </a-upload>     
          <a-dropdown>
            <!-- <a-menu slot="overlay">
              <a-menu-item key="1" v-if="btnEnableList.indexOf(1)>-1" @click="categoryBatchDel"><a-icon type="delete"/>删除</a-menu-item>          
            </a-menu> -->
            <!--把批量删除 这行先去掉 感觉弄不好 好多分类就直接删除了 很可怕-->
            <!-- <a-button>
              批量删除 <a-icon type="down" />
            </a-button> -->
          </a-dropdown>
          <a-popover trigger="click" placement="right">
            <template slot="content">
              <a-checkbox-group @change="onColChange" v-model="settingColumns" :defaultValue="settingColumns">
                <a-row style="width: 500px">
                  <template v-for="(item,index) in defColumns">
                    <template>
                      <a-col :span="8" :key="index">
                        <a-checkbox :value="item.dataIndex">
                          <j-ellipsis :value="item.title" :length="10"></j-ellipsis>
                        </a-checkbox>
                      </a-col>
                    </template>
                  </template>
                </a-row>
              </a-checkbox-group>
            </template>
      
          </a-popover>
        </div>    
       <div>
          <a-table
            ref="table"
            size="middle"
            bordered
            rowKey="id"        
            :columns="columns_main"
            :dataSource="data"
            :pagination="ipagination"
            :scroll="scroll"
            :loading="loading" 
            checkStrictly=false 
            :rowSelection="{selectedRowKeys: selectedRowKeys, onChange: onSelectChange,columnWidth:'2%'}"
            @change="handleTableChange">
            <span slot="action" slot-scope="text, record">
              <a v-if="record.parentid==undefined" @click="handleEditProject(record)">编辑项目</a>
            
              <a  v-if="record.parentid!=undefined" @click="handleEditSubTable(record)" >编辑子表</a>
              <a-divider v-if="btnEnableList.indexOf(1)>-1" type="vertical" />
              <a-popconfirm  title="确定删除吗?" @confirm="() => handleDelete(record.id)" >
                <a>删除</a>
              </a-popconfirm>
            </span>
                <template slot="customRenderEnabled" slot-scope="enabled">
              <a-tag v-if="enabled" color="green">启用</a-tag>
              <a-tag v-if="!enabled" color="orange">禁用</a-tag>
            </template>
            <template slot="customRenderEnableSerialNumber" slot-scope="enableSerialNumber">
              <a-tag v-if="enableSerialNumber==1" color="green">有</a-tag>
              <a-tag v-if="enableSerialNumber==0" color="orange">无</a-tag>
            </template>
            <template slot="customRenderEnableBatchNumber" slot-scope="enableBatchNumber">
              <a-tag v-if="enableBatchNumber==1" color="green">有</a-tag>
              <a-tag v-if="enableBatchNumber==0" color="orange">无</a-tag>
            </template>
          </a-table>   
        </div>
        <!-- table区域-end -->
        <!-- 表单区域 -->
        <!--material-modal是新增修改项目的model框-->
        <material-modal ref="modalForm" @ok="projectmodalFormOk"></material-modal>
        <!--MaterialSubModal是新增修改子表的model框-->
        <MaterialSubModal ref="modalsubForm" @subok="submodalFormOk"  @sueditok="submodalFormOkEdit"></MaterialSubModal>
          <!--MaterialAddDetailModal是新增修改子表具体内容的model框-->
        <MaterialAddDetailModal ref="modaladddetailForm" @detailok="adddetailmodalFormOk"></MaterialAddDetailModal>
        <batch-set-info-modal ref="batchSetInfoModalForm" @ok="modalFormOk"></batch-set-info-modal>
      </a-card>
    </a-col>
  </a-row>
</template>
<script>
  import MaterialModal from './modules/MaterialAddModal'
  import MaterialSubModal from './modules/MaterialAddSubModal'
  import MaterialAddDetailModal from './modules/MaterialAddDetailModal'
  import BatchSetInfoModal from './modules/BatchSetInfoModal'
  import { queryMaterialCategoryTreeList,getProjectList } from '@/api/api'
  import { postAction } from '@/api/manage'
  import { getMpListShort } from '@/utils/util'
  import { JeecgListMixin } from '@/mixins/JeecgListMixin'
  import JEllipsis from '@/components/jeecg/JEllipsis'
  import JDate from '@/components/jeecg/JDate'
  import Vue from 'vue'


  const columns_main = [
    // { title:"项目ID", dataIndex: 'id'},
    { title: '项目名', dataIndex: 'name'},
    // { title: '子表名', dataIndex: 'subname'},
    { title: '截止日期', dataIndex: 'endtime'},
    { title: '总数', dataIndex: 'num'},
    { title: '负责人', dataIndex: 'manager'},
    { title: '项目编号', dataIndex: 'prono'},
    { title: '操作', scopedSlots: { customRender: 'action' } },
  
  ];

  const innerColumns = [   
    { title: '图号', dataIndex: 'image_num', key: 'image_num' },
    { title: '名称', dataIndex: 'name', key: 'name' },
    { title: '材质', dataIndex: 'makeup', key: 'makeup'},
    { title: '工艺要求', dataIndex: 'tech', key: 'tech'},
    { title: '件数', dataIndex: 'nums', key: 'nums' },
    { title: '备注', dataIndex: 'remark', key: 'remark' },
    { title: '表面处理', dataIndex: 'ext2', key: 'ext2' },
    { title: '单位', dataIndex: 'ext3', key: 'ext3' },
    { title: '仓库', dataIndex: 'ext4', key: 'ext4' },
    { title: '检验', dataIndex: 'ext5', key: 'ext5' },
    { title: '申领', dataIndex: 'ext6', key: 'ext6' },
    { title: '采购件', dataIndex: 'ext7', key: 'ext7' },
    { title: '版本', dataIndex: 'ext8', key: 'ext8' },
    { title: '品牌', dataIndex: 'ext9', key: 'ext9' },
    { title: '单台数量', dataIndex: 'ext10', key: 'ext10' },
    {
      title: '操作',
      dataIndex: 'operation',
      key: 'operation',
      scopedSlots: { customRender: 'action_new' },
    },
  ];

  export default {
    name: "MaterialAdd",
    mixins:[JeecgListMixin],
    components: {
      MaterialModal,
      MaterialSubModal,
      MaterialAddDetailModal,
      BatchSetInfoModal,
      JEllipsis,
      JDate
    },
    mounted(){        
    },
    data () {
      return {
        data: [],
        columns_main,
        innerColumns,   
        expandedRowKeys: [],
        categoryTree:[],
        mPropertyListShort: '',
        model: {},
        labelCol: {
          span: 5
        },
        wrapperCol: {
          span: 18,
          offset: 1
        },
        // 查询条件
        queryParam: {
          categoryId:'',
          materialParam:'',
          color:'',
          weight:'',
          expiryNum:'',
          enabled: '',
          enableSerialNumber:'',
          enableBatchNumber:'',
          remark:'',
          mpList: getMpListShort(Vue.ls.get('materialPropertyList'))  //扩展属性
        },
        ipagination:{
          pageSizeOptions: ['10', '20', '30', '100', '200']
        },
        // 实际表头
        columns:[],
        // 初始化设置的表头
        settingColumns:['mBarCode','name','standard','model','color','categoryName','materialOther','unit', 'stock',
          'purchaseDecimal','commodityDecimal','wholesaleDecimal','lowDecimal','enabled','enableSerialNumber','enableBatchNumber','action'],
        // 默认的列      
         defColumns: [
            { title:"项目ID", dataIndex: 'id'},
            { title: '项目名', dataIndex: 'name'},
            { title: '子表名', dataIndex: 'subname'},
            { title: '截止日期', dataIndex: 'endtime'},
            { title: '总数', dataIndex: 'num'},
            { title: '负责人', dataIndex: 'manager'},
            { title: '项目编号', dataIndex: 'prono'},
            { title: '操作', scopedSlots: { customRender: 'action' }}
        ],
        url: {
          list: "/material/list",
          delete: "/material/delete",
          deleteBatch: "/material/deleteBatch",
          importExcelUrl: "/material/importExcel",
          exportXlsUrl: "/material/exportExcel",
          batchSetStatusUrl: "/material/batchSetStatus",
          batchSetMaterialCurrentStockUrl: "/material/batchSetMaterialCurrentStock"
        }
      }
    },
    created() {
      this.init() // 获取主表格数据
      this.model = Object.assign({}, {});
      //this.initColumnsSetting()  //获得this.colums
      this.loadTreeData();
    },
    computed: {
      importExcelUrl: function () {
        return `${window._CONFIG['domianURL']}${this.url.importExcelUrl}`;
      }
    },
    methods: {
        /*
    * 功能：表格展开行的集合
    * 参数：expandedRowKeys:展开行的key形成的数组
    */
    expandedRowsChange(expandedRowKeys) {    
      this.expandedRowKeys = expandedRowKeys
    },
    /*
   * 功能：加载主表格数据
   * 说明：此处采用键值对的形式，是为了避免全部子表格数据相同
   */
    init() {
      let params = {}
      params.tenant_id = 63

      let DataSource = []
      getProjectList(params).then((res)=>{
        res.forEach(function(item, index){
         
          let tmp_json = {}
          tmp_json.name = item.name
          tmp_json.id = item.id
          if(item.endtime == undefined){
            tmp_json.endtime = ""
          }else{
              tmp_json.endtime = item.endtime
          }
          if(item.num == undefined){
            tmp_json.num = ""
          }else{
              tmp_json.num = item.num
          }

          if(item.manager == undefined){
            tmp_json.manager = ""
          }else{
              tmp_json.manager = item.manager
          }

          if(item.prono == undefined){
            tmp_json.prono = ""
          }else{
              tmp_json.prono = item.prono
          }

          tmp_json.children = []


          if(item.childrens.length == 0){
            tmp_json.children = []

          }else{
            let childrens = item.childrens
            childrens.forEach(function(sub_item,sub_index){
              let  children_tmp_json = {}
              children_tmp_json.name = sub_item.name
              children_tmp_json.id = sub_item.id
              children_tmp_json.parentid = sub_item.parentid
              children_tmp_json.enabled = true
              tmp_json.children.push(children_tmp_json)
            })
          }

          DataSource.push(tmp_json)
        })
        this.data = DataSource
      }) 
    },
    projectQuery(){ //查询工程名称
      let keywords = this.$refs.search.value  
      let search_datasource = []
      let tmp_data = this.data

      let search_data = []

      tmp_data.forEach((item, index)=>{
        if(item.name.indexOf(keywords) != -1){
          search_data.push(item)         

        }
      })

      this.data = search_data
    },
     /*
    * 功能：添加主表格一行
    */
    add() {
      let i = this.data.length // 保证key唯一
      this.data.push({
        key: i,
        name: `第${ i + 1 }行`,
        sex: `女${ i + 1 }`,
        age: '12',
        hobby: '吃饭',
        innerData: []
      })
    },
    /*
    * 功能：添加子表格一行
    * 参数：row：点击行的信息
    */
    addInnderData(row) {
      // 只有当这一行展开时，点击添加子表格才会有数据。
      if (this.expandedRowKeys.includes(row.key)) {
        let i = row.key * 10 + row.innerData.length + 1
        this.data.forEach(item => {
          if (item.key === row.key) {
            item.innerData.push({
              key: i,
              name: '哦哦',
              sex: '男',
              age: '12',
              hobby: '吃饭',
            })
          }
        })
      }
    },
    /*
    * 功能：点击某行加号，加载子表格数据
    * 参数：expanded：是否展开 
    * 参数：record：点击行的数据
    */
    getInnerData(expanded, record) {
      if (expanded) { // 当展开子表格时，才会加载子表格数据
        let categoryId = record.childid;
        this.loadDataDetail(categoryId)

      }      
    },
    onChange: (selectedRowKeys, selectedRows) => {
      console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
    },
    // onSelect: (record, selected, selectedRows) => {
    //   console.log(record, selected, selectedRows);
    // },
    onSelectAll: (selected, selectedRows, changeRows) => {
      console.log(selected, selectedRows, changeRows);
    },

    //加载初始化列
    initColumnsSetting(){
      let columnsStr = Vue.ls.get('materialColumns')  //写入缓存的类 只有勾选了需要显示那些列的时候 彩绘出发 set('materialColumns')

      if(columnsStr && columnsStr.indexOf(',')>-1) {
        this.settingColumns = columnsStr.split(',')
      }
    
      this.columns = this.defColumns.filter(item => {
        if (this.settingColumns.includes(item.dataIndex)) { //(this.settingColumns是有默认值的          
          return true
        }
        return false
      })    
    },
      //列设置更改事件
      onColChange (checkedValues) {
        this.columns = this.defColumns.filter(item => {
          if (checkedValues.includes(item.dataIndex)) {
            return true
          }
          return false
        })
        let columnsStr = checkedValues.join()
        Vue.ls.set('materialColumns', columnsStr)
      },
      loadTreeData(){
        let that = this;
        let params = {};
        params.id='';
        queryMaterialCategoryTreeList(params).then((res)=>{      
          //  console.log(res) //这个返回的是跟目录 比如//目录1  0625构建盘
          if(res){
            that.categoryTree = [];
            for (let i = 0; i < res.length; i++) {
              let temp = res[i];
              that.categoryTree.push(temp);
            }
          }
        })
      },
      batchSetMaterialCurrentStock () {
        if (this.selectedRowKeys.length <= 0) {
          this.$message.warning('请选择一条记录！');
        } else {
          let ids = "";
          for (let a = 0; a < this.selectedRowKeys.length; a++) {
            ids += this.selectedRowKeys[a] + ",";
          }
          let that = this;
          this.$confirm({
            title: "确认操作",
            content: "是否操作选中数据?",
            onOk: function () {
              that.loading = true;
              postAction(that.url.batchSetMaterialCurrentStockUrl, {ids: ids}).then((res) => {
                if(res.code === 200){
                  that.$message.info('修正库存成功！');
                  that.loadData();
                  that.onClearSelected();
                } else {
                  that.$message.warning(res.data.message);
                }
              }).finally(() => {
                that.loading = false;
              });
            }
          });
        }
      },
      batchEdit() {
        if (this.selectedRowKeys.length <= 0) {
          this.$message.warning('请选择一条记录！');
        } else {
          let ids = "";
          for (let a = 0; a < this.selectedRowKeys.length; a++) {
            ids += this.selectedRowKeys[a] + ",";
          }
          this.$refs.batchSetInfoModalForm.edit(ids);
          this.$refs.batchSetInfoModalForm.title = "批量编辑";
        }
      },
      handleEdit: function (record) {
        this.$refs.modalForm.edit(record);
        this.$refs.modalForm.title = "编辑";
        this.$refs.modalForm.disableSubmit = false;
        if(this.btnEnableList.indexOf(1)===-1) {
          this.$refs.modalForm.isReadOnly = true
        }
      },
      searchReset() {
        this.queryParam = {
          mpList: getMpListShort(Vue.ls.get('materialPropertyList'))  //扩展属性
        }
        //this.loadData(1);
        this.init();
      },
      submodalFormOk(){// wcw 增加新项目子表后重新组织数据 显示新增的行            
        this.init()
      },
      submodalFormOkEdit(){ //编辑子表名后重新加载      
        this.init()
      },
      adddetailmodalFormOk(){ //wcw
        //重新请求数据 组织数据，把嵌套列表显示出来 wcw      
        this.loadDataDetail();  //这个是重新加载子表格数据
      },
      projectmodalFormOk(){
        //修改过项目后重新加载项目
        this.init()
      }
    },  
  }
</script>
<style scoped>
  @import '~@assets/less/common.less'
</style>